package org.practice.validate;

import java.util.*;

/**
 * jQuery-validation插件验证规则的生成器
 * 根据bean的Annotation构造相应的封装对象(如：JSValidationLengthImpl),然后再生成JS
 */
public class JSValidationGenerator {
    /**
     * Map: key是fieldname，value是这个field对应的Annotation集合
     */
    private Map<String,List<JSValidation>> fieldAnnotaionMap=new LinkedHashMap<String, List<JSValidation>>();
    public String generate(){
        StringBuffer rulesBuffer=new StringBuffer("\trules: {\n");
        StringBuffer messagesBuffer=new StringBuffer("\tmessages: {\n");
        for (Iterator<String> iterator = fieldAnnotaionMap.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            List<JSValidation> valueList=fieldAnnotaionMap.get(key);
            rulesBuffer.append("\t\tmodel.").append(key).append(": {\n").append(getRules(valueList)).append("\n\t\t}");
            messagesBuffer.append("\t\tmodel.").append(key).append(":{\n").append(getMessages(valueList)).append("\n\t\t}");
            if(iterator.hasNext()){
                rulesBuffer.append(",\n");
                messagesBuffer.append(",\n");
            }
        }
        rulesBuffer.append("\n\t}");
        messagesBuffer.append("\n\t}\n");

        StringBuffer resultBuffer=new StringBuffer("var rules_obj={\n").append(rulesBuffer).append(",\n").append(messagesBuffer).append("};");
        return  resultBuffer.toString();
    }

    private StringBuffer getMessages(List<JSValidation> valueList) {
        StringBuffer result=new StringBuffer();
        for (Iterator<JSValidation> iterator = valueList.iterator(); iterator.hasNext(); ) {
        	JSValidation annotation = iterator.next();
            result.append(annotation.getMessage());
            if(iterator.hasNext()){
                result.append(",\n");
            }else{
                result.append("\n");
            }
        }
        return result;
    }

    private StringBuffer getRules(List<JSValidation> valueList) {
        StringBuffer result=new StringBuffer();
        for (Iterator<JSValidation> iterator = valueList.iterator(); iterator.hasNext(); ) {
        	JSValidation annotation = iterator.next();
            result.append(annotation.getRule());
            if(iterator.hasNext()){
                result.append(",\n");
            }else{
                result.append("\n");
            }
        }
        return result;
    }
    
    public void addFieldValidation(String fieldName,JSValidation jsValidation){
         List<JSValidation> valueList=fieldAnnotaionMap.get(fieldName);
        if(valueList==null){
            valueList=new ArrayList<JSValidation>();
            valueList.add(jsValidation);
            fieldAnnotaionMap.put(fieldName,valueList);
        }else{
            valueList.add(jsValidation);
        }
    }
}
